package com.iscas.green.extralindextest.config;

import com.clickhouse.jdbc.ClickHouseDataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class ClickHouseConfig {
    
    @Value("${clickhouse.datasource.jdbc-url}")
    private String jdbcUrl;
    
    @Value("${clickhouse.datasource.username}")
    private String username;
    
    @Value("${clickhouse.datasource.password}")
    private String password;
    
    @Value("${clickhouse.datasource.driver-class-name}")
    private String driverClassName;
    
    @Bean(name = "clickhouseDataSource")
    public DataSource clickhouseDataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);
        
        // 设置连接池属性
        dataSource.setMaximumPoolSize(10);
        dataSource.setMinimumIdle(2);
        dataSource.setIdleTimeout(30000);
        dataSource.setMaxLifetime(1800000);
        dataSource.setConnectionTimeout(20000);
        
        // 设置数据源属性
        Properties dsProps = new Properties();
        dsProps.setProperty("socket_timeout", "300000");
        dsProps.setProperty("compress", "0"); // 禁用压缩
        dsProps.setProperty("decompress", "0"); // 禁用解压缩
        dsProps.setProperty("use_server_time_zone", "false");
        
        dataSource.setDataSourceProperties(dsProps);
        
        return dataSource;
    }
    
    @Bean(name = "clickhouseJdbcTemplate")
    public JdbcTemplate clickhouseJdbcTemplate(@Qualifier("clickhouseDataSource") DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        // 设置查询超时
        jdbcTemplate.setQueryTimeout(30);
        return jdbcTemplate;
    }
} 